// content.js

function showBubble(mainMessage, detailMessage = '') {
    if (window.self !== window.top) {
        return;
    }

    const bubble = document.createElement('div');
    bubble.className = 'extension-copy-bubble';

    const mainEl = document.createElement('div');
    mainEl.textContent = mainMessage;
    mainEl.style.fontWeight = 'bold';
    bubble.appendChild(mainEl);

    if (detailMessage) {
        const detailEl = document.createElement('div');
        detailEl.textContent = detailMessage;
        detailEl.style.fontSize = '12px';
        detailEl.style.opacity = '0.9';
        detailEl.style.marginTop = '4px';
        detailEl.style.whiteSpace = 'nowrap';
        detailEl.style.overflow = 'hidden';
        detailEl.style.textOverflow = 'ellipsis';
        bubble.appendChild(detailEl);
    }

    document.body.appendChild(bubble);

    const onEnd = () => {
        if (bubble.parentNode) {
            bubble.parentNode.removeChild(bubble);
        }
        bubble.removeEventListener('animationend', onEnd);
        bubble.removeEventListener('animationcancel', onEnd);
    };

    bubble.addEventListener('animationend', onEnd);
    bubble.addEventListener('animationcancel', onEnd);
}

// 根据 XPath 获取文本内容，并返回是否存在
function getTextByXPath(xpath) {
    const result = document.evaluate(
        xpath,
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
    );
    const node = result.singleNodeValue;
    if (node) {
        return {
            text: node.textContent.trim(),
            found: true
        };
    } else {
        return {
            text: '',
            found: false
        };
    }
}

// 尝试多个 XPath，返回第一个找到的（无 try-catch）
function getTextByXPathList(xpaths) {
    for (const xpath of xpaths) {
        const result = document.evaluate(
            xpath,
            document,
            null,
            XPathResult.FIRST_ORDERED_NODE_TYPE,
            null
        );
        const node = result.singleNodeValue;
        if (node) {
            const text = node.textContent.trim();
            // 可选：跳过空文本（根据需求决定是否保留）
            if (text !== '') {
                return { text, found: true };
            }
        }
    }
    return { text: '', found: false };
}

// 检查自动提取设置
async function isAutoExtractEnabled() {
    // ✅ 默认值设为 true（首次安装时自动开启）
    const result = await chrome.storage.local.get({ autoExtractEnabled: true });
    return result.autoExtractEnabled;
}

async function copyTextToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        return true;
    } catch (err) {
        console.error('复制失败:', err);
        return false;
    }
}

// 检查是否处于录制模式
async function isRecording() {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage({ action: "getRecordingStatus" }, (response) => {
            resolve(response?.isRecording || false);
        });
    });
}

// 🔑 核心功能：提取并复制
async function extractAndCopy() {
    const corp_name_xpath = [
        '/html/body/div/div[2]/div[1]/div[1]/div/div[1]/div[2]/div[1]/div[1]/div/div/div/span/span[1]/h1',
        '/html/body/div[1]/div[2]/div[2]/div[1]/div/div[1]/div[2]/div[1]/div[1]/div/div/div/span/span[1]/h1'
    ];
    const reg_id_xpath = [
        '//*[@id="cominfo"]/div[2]/div[2]/table/tr[4]/td[4]/span/span[1]',
        '//*[@id="cominfo"]/div[2]/div[2]/table/tr[4]/td[4]/span'
    ];
    const uni_id_xpath = ['//*[@id="cominfo"]/div[2]/div[2]/table/tr[1]/td[2]/span/span[1]', '//*[@id="cominfo"]/div[2]/div[2]/table/tr[1]/td[2]/span'];

    // ✅ 修正：去掉 /text()，直接选 td 元素
    const reg_id_check_xpath = '//*[@id="cominfo"]/div[2]/div[2]/table/tr[4]/td[3]';
    const uni_id_check_xpath = '//*[@id="cominfo"]/div[2]/div[2]/table/tr[1]/td[1]';

    // 获取主数据
    const corp = getTextByXPathList(corp_name_xpath);
    const reg = getTextByXPathList(reg_id_xpath);
    const uni = getTextByXPathList(uni_id_xpath);

    // 获取校验标签
    const regLabel = getTextByXPath(reg_id_check_xpath);
    const uniLabel = getTextByXPath(uni_id_check_xpath);

    // 🔍 检查主字段是否存在
    if (!corp.found || !reg.found || !uni.found) {
        console.warn('❌ 主字段获取失败', { corp, reg, uni });
        showBubble("❌ 页面结构变化，信息获取失败。");
        return;
    }

    // 🔍 检查校验字段是否存在
    if (!regLabel.found || !uniLabel.found) {
        console.warn('❌ 校验标签未找到', { regLabel, uniLabel });
        showBubble("❌ 页面结构变化，信息获取失败。");
        return;
    }

    // 🔍 检查标签文本是否匹配预期
    const expectedRegLabel = "工商注册号";
    const expectedUniLabel = "统一社会信用代码";

    // 使用 trim() 避免空格干扰
    if (regLabel.text.trim() !== expectedRegLabel || uniLabel.text.trim() !== expectedUniLabel) {
        console.warn('❌ 标签内容不匹配', {
            actualReg: regLabel.text,
            actualUni: uniLabel.text,
            expectedReg: expectedRegLabel,
            expectedUni: expectedUniLabel
        });
        showBubble("❌ 页面结构变化，信息获取失败。");
        return;
    }

    // ✅ 通过校验，处理数据
    let corp_name_str = corp.text;
    let reg_id_str = reg.text;
    let uni_id_str = uni.text;

    if (reg_id_str.length < 3) reg_id_str = '不适用';
    if (uni_id_str.length < 3) uni_id_str = '不适用';

    console.log('【自动/快捷键】提取内容:', { corp_name_str, reg_id_str, uni_id_str });
    const combined = `${corp_name_str}\t${reg_id_str}\t${uni_id_str}\t中国`;

    // 读取自动换行设置
    const settings = await chrome.storage.local.get({ autoWrapEnabled: false });
    const separator = settings.autoWrapEnabled ? '\n' : '';
    const success = await copyTextToClipboard(`${combined}${separator}`);

    if (!success) {
        showBubble("❌ 自动复制失败。");
        return;
    }

    // ✅ 新增：检查是否在录制模式
    const recording = await isRecording();
    let succeess_info = `✅ 已复制结果到剪贴板`;
    if (recording) {
        // 发送结果给 background 累加
        chrome.runtime.sendMessage(
            {
                action: "recordResult",
                data: `${combined}\n`
            },
            (response) => {
                if (response?.success) {
                    const count = response.currentCount;
                    succeess_info = `✅ 已复制并保存结果，当前已保存${count}条`;
                } else {
                    succeess_info = `❌ 已复制结果但保存失败`;
                }
                showBubble(succeess_info, combined);
            }
        );
        console.log("✅ 已发送记录", combined);
        return;
    }
    showBubble(succeess_info, combined);
}


// 📥 监听来自 background 的消息（快捷键触发）
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "extractAndCopy") {
        extractAndCopy();
    }
});

// 🚀 页面加载完成后自动触发
// ===== 自动触发逻辑（防重复 + 仅主窗口）=====
let autoTriggered = false;

async function scheduleAutoExtract() {
    // 仅在顶层页面执行
    if (window.self !== window.top) return;
    if (autoTriggered) return;

    // 🔑 新增：检查用户是否启用了自动提取
    const enabled = await isAutoExtractEnabled();
    if (!enabled) {
        console.log('ℹ️ 自动提取已禁用');
        return;
    }

    autoTriggered = true;
    setTimeout(extractAndCopy, 500);
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', scheduleAutoExtract);
} else {
    scheduleAutoExtract();
}